﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using Caliburn.Micro;
using HtmlAgilityPack;
using Wulong.Phone.Qiushi.Models;

namespace Wulong.Phone.Qiushi.ViewModels.Coroutines
{
    public class CommentsLoader : IResult
    {
        private const string BaseUrl = "http://www.qiushibaike.com";

        private static IObservable<QiushiComment> GetObservableComment(int id)
        {
            const string commentsQuery = BaseUrl + "/new2/comment/{0}";
            return
                (from request in
                     Observable.Return((HttpWebRequest)WebRequest.Create(new Uri(string.Format(commentsQuery, id))))
                     .Catch<HttpWebRequest, Exception>(e => Observable.Empty<HttpWebRequest>())
                 from response in
                     Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Catch(Observable.Empty<WebResponse>())
                 from item in GetComments(response.GetResponseStream()).ToObservable().Catch(Observable.Empty<QiushiComment>())
                 select item).ObserveOnDispatcher();
        }

        private static IEnumerable<QiushiComment> GetComments(Stream stream)
        {
            var doc = new HtmlDocument();
            doc.Load(stream);
            var nodes = from n in doc.DocumentNode.Descendants("div")
                        where
                            n.HasAttributes && n.Attributes[0].Value.Equals("clearfix")
                        select n;
            return nodes.Select(BuildQiushiComment);
        }

        private static QiushiComment BuildQiushiComment(HtmlNode node)
        {
            var item = new QiushiComment();
            var commentNodes = node.Elements("div");
            foreach (var commentNode in commentNodes)
            {
                if (commentNode.Attributes["class"].Value.Equals("avatar"))
                {
                    item.Avatar = commentNode.Element("img").Attributes["src"].Value;
                }
                if (commentNode.Attributes["class"].Value.Equals("reply"))
                {
                    item.Author = commentNode.Element("a").InnerText;
                    item.Body = commentNode.Element("span").InnerText;
                }
                if (commentNode.Attributes["class"].Value.Equals("report"))
                {
                    item.Floor = commentNode.Element("span").InnerText + "L";
                }
            }
            return item;
        }

        public void Execute(ActionExecutionContext context)
        {
            throw new NotImplementedException();
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}
